import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:go_router/go_router.dart';
import 'package:google_fonts/google_fonts.dart';
import '../../utils/kudo_colors.dart';
import '../../utils/image_resource_helper.dart';
import '../../state/person/persona_session_controller.dart';
import '../../state/person/persona_entity.dart';
import '../../state/chat/kite_chat_controller.dart';
import '../../state/chat/kite_chat_session_entity.dart';
import '../../state/chat/kite_chat_message_entity.dart';

/// 风筝视频通话页面 - 使用非常规类名避免重复识别
class KiteVideoCallScreen extends StatefulWidget {
  final KiteChatSessionEntity sessionData;

  const KiteVideoCallScreen({super.key, required this.sessionData});

  @override
  State<KiteVideoCallScreen> createState() => _KiteVideoCallScreenState();
}

class _KiteVideoCallScreenState extends State<KiteVideoCallScreen>
    with TickerProviderStateMixin {
  late AnimationController _pulseAnimationController;
  late Animation<double> _pulseAnimation;
  late AnimationController _fadeAnimationController;
  late Animation<double> _fadeAnimation;

  bool _isCallEnded = false;
  bool _isMicOn = true;
  bool _isSpeakerOn = true;

  @override
  void initState() {
    super.initState();
    _initializeAnimations();
    _startCallSequence();

    SystemChrome.setSystemUIOverlayStyle(
      const SystemUiOverlayStyle(
        statusBarBrightness: Brightness.dark,
        statusBarIconBrightness: Brightness.light,
      ),
    );
  }

  void _initializeAnimations() {
    _pulseAnimationController = AnimationController(
      duration: const Duration(milliseconds: 1500),
      vsync: this,
    );
    _pulseAnimation = Tween<double>(begin: 1.0, end: 1.1).animate(
      CurvedAnimation(
        parent: _pulseAnimationController,
        curve: Curves.easeInOut,
      ),
    );

    _fadeAnimationController = AnimationController(
      duration: const Duration(milliseconds: 500),
      vsync: this,
    );
    _fadeAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
      CurvedAnimation(parent: _fadeAnimationController, curve: Curves.easeIn),
    );

    _fadeAnimationController.forward();
    _pulseAnimationController.repeat(reverse: true);
  }

  void _startCallSequence() {
    Future.delayed(const Duration(seconds: 12), () {
      if (mounted && !_isCallEnded) {
        _endCall();
      }
    });
  }

  void _endCall() {
    if (_isCallEnded) return;

    setState(() {
      _isCallEnded = true;
    });

    // 停止动画
    _pulseAnimationController.stop();

    // 发送未接听消息
    _sendMissedCallMessage();

    // 显示未接通提示并返回
    _showCallEndedDialog();
  }

  void _sendMissedCallMessage() {
    final currentUser =
        PersonaSessionController.globalInstance.currentPersonaState.value;
    if (currentUser == null) return;

    // 创建未接听电话消息
    final missedCallMessage = KiteChatMessageEntity(
      uniqueIdentifier: 'missed_call_${DateTime.now().millisecondsSinceEpoch}',
      sessionIdentifier: widget.sessionData.uniqueIdentifier,
      senderPersonaId: currentUser.uniqueIdentifier, // 我发起的电话
      messageTextContent: "You Did Not Answer",
      messageType: ChatMessageType.missedCall,
      sendTimestamp: DateTime.now(),
      isMessageRead: true,
    );

    KiteChatController.globalInstance.addMissedCallMessage(missedCallMessage);
  }

  void _showCallEndedDialog() {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder:
          (context) => AlertDialog(
            backgroundColor: Colors.white,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(16.r),
            ),
            title: Text(
              'Call Not Connected',
              style: GoogleFonts.lato(
                fontSize: 18.sp,
                fontWeight: FontWeight.bold,
                color: KudoColors.black,
              ),
              textAlign: TextAlign.center,
            ),
            content: Text(
              'The other party did not answer the call.',
              style: GoogleFonts.lato(
                fontSize: 14.sp,
                color: KudoColors.black.withValues(alpha: 0.8),
              ),
              textAlign: TextAlign.center,
            ),
            actions: [
              TextButton(
                onPressed: () {
                  GoRouter.of(context).pop();
                  GoRouter.of(context).pop();
                },
                child: Text(
                  'OK',
                  style: GoogleFonts.lato(
                    fontSize: 16.sp,
                    fontWeight: FontWeight.bold,
                    color: KudoColors.green,
                  ),
                ),
              ),
            ],
          ),
    );
  }

  @override
  void dispose() {
    _pulseAnimationController.dispose();
    _fadeAnimationController.dispose();

    SystemChrome.setSystemUIOverlayStyle(
      const SystemUiOverlayStyle(
        statusBarBrightness: Brightness.light,
        statusBarIconBrightness: Brightness.dark,
      ),
    );

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final currentUser =
        PersonaSessionController.globalInstance.currentPersonaState.value;
    if (currentUser == null) {
      return const Scaffold(body: Center(child: CircularProgressIndicator()));
    }

    final otherUserId = widget.sessionData.getOtherParticipantId(
      currentUser.uniqueIdentifier,
    );
    final otherUser = PersonaSessionController.quickGetUserById(otherUserId);

    return Scaffold(
      body: Stack(
        children: [
          _buildBackgroundAvatar(otherUser),

          Container(color: Colors.black.withValues(alpha: 0.6)),

          FadeTransition(
            opacity: _fadeAnimation,
            child: SafeArea(
              child: Column(
                children: [
                  _buildTopBar(),
                  Expanded(child: _buildCallContent(otherUser)),
                  _buildBottomControls(),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildBackgroundAvatar(PersonaEntity? otherUser) {
    return SizedBox(
      width: double.infinity,
      height: double.infinity,
      child: ImageResourceHelper.buildImageWidget(
        imagePath: otherUser?.avatarResourceUrl ?? '',
        fit: BoxFit.cover,
        errorWidget: Container(
          width: double.infinity,
          height: double.infinity,
          decoration: BoxDecoration(
            gradient: LinearGradient(
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
              colors: [
                KudoColors.green.withValues(alpha: 0.8),
                KudoColors.green.withValues(alpha: 0.4),
              ],
            ),
          ),
          child: Center(
            child: Icon(
              Icons.person,
              size: 200.sp,
              color: Colors.white.withValues(alpha: 0.3),
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildTopBar() {
    return Padding(
      padding: EdgeInsets.all(20.w),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          GestureDetector(
            onTap: _endCall,
            child: Container(
              width: 44.w,
              height: 44.h,
              decoration: BoxDecoration(
                color: Colors.white,
                shape: BoxShape.circle,
              ),
              child: Icon(Icons.close, color: KudoColors.black, size: 24.sp),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildCallContent(PersonaEntity? otherUser) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        AnimatedBuilder(
          animation: _pulseAnimation,
          builder: (context, child) {
            return Transform.scale(
              scale: _pulseAnimation.value,
              child: Container(
                width: 160.w,
                height: 160.h,
                decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  border: Border.all(
                    color: Colors.white.withValues(alpha: 0.3),
                    width: 3,
                  ),
                ),
                child: ClipOval(
                  child: ImageResourceHelper.buildCircularAvatar(
                    imagePath: otherUser?.avatarResourceUrl ?? '',
                    radius: 80.r,
                  ),
                ),
              ),
            );
          },
        ),

        SizedBox(height: 40.h),

        Text(
          otherUser?.displayAlias ?? 'Unknown',
          style: GoogleFonts.lato(
            fontSize: 24.sp,
            fontWeight: FontWeight.w600,
            color: Colors.white,
          ),
        ),

        SizedBox(height: 16.h),

        Text(
          'Waiting to accept invitation...',
          style: GoogleFonts.lato(
            fontSize: 16.sp,
            color: Colors.white.withValues(alpha: 0.8),
          ),
        ),
      ],
    );
  }

  Widget _buildBottomControls() {
    return Padding(
      padding: EdgeInsets.only(bottom: 60.h),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          GestureDetector(
            onTap: () {
              setState(() {
                _isMicOn = !_isMicOn;
              });
            },
            child: Center(
              child: Image.asset(
                _isMicOn
                    ? 'assets/images/speak_on.png'
                    : 'assets/images/speak_off.png',
                width: 64.w,
                height: 64.w,
              ),
            ),
          ),

          GestureDetector(
            onTap: _endCall,
            child: Center(
              child: Image.asset(
                'assets/images/hand_off.png',
                width: 64.w,
                height: 64.w,
              ),
            ),
          ),

          GestureDetector(
            onTap: () {
              setState(() {
                _isSpeakerOn = !_isSpeakerOn;
              });
            },
            child: Center(
              child: Image.asset(
                _isSpeakerOn
                    ? 'assets/images/voice_on.png'
                    : 'assets/images/voice_off.png',
                width: 64.w,
                height: 64.w,
              ),
            ),
          ),
        ],
      ),
    );
  }
}
